#include "broadcast_bang_client_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"
#include "im/adapters/bang_robot_adapter.h"

namespace imserver {
namespace fcgi {

bool BroadcastBangClientRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  ParseUserIdentity();

  std::stringstream rsp_body;
  rsp_body << "OK";
  std::stringstream rsp_header;
  rsp_header << "Content-type: text/html; charset=utf-8\r\nContent-Length: " << rsp_body.str().size() << "\r\n\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  int64_t shop_id = 0;
  try {
    shop_id = boost::lexical_cast<int64_t>(GetQuery("s"));
  } catch (boost::bad_lexical_cast&) {}

  if (effective_id() > 0 && shop_id > 0) {
    std::string question = GetQuery("q");
    if (question.empty()) {
      BangRobotAdapter::Instance().BroadcastClient(effective_id(), shop_id, 2);
    } else {
      LOG_INFO("Bang robot broadcast with question=" << question);
      BangRobotAdapter::Instance().BroadcastClientWithQuestion(effective_id(), shop_id, question, 2);
    }
  }

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);

  LOG_INFO("BroadcastBangClientRequest uid=" << effective_id());
  return true;
}

}
}


